<template>
  <div ref="chartEl" id="bar-chart"></div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import 'echarts/theme/macarons';

// 定义 props
const props = defineProps({
  xAxisData: {
    type: Array,
    required: true,
  },
  visitUserNumData: {
    type: Array,
    required: true,
  },
  visitNumData: {
    type: Array,
    required: true,
  },
});

const chartEl = ref();
let chartInstance: echarts.ECharts | null = null;

// 初始化图表
const initChart = (
  xAxisData: any,
  visitUserNumData: any,
  visitNumData: any,
) => {
  console.log(
    chartEl.value,
    'There is a chart instance already initialized on the dom.',
  );
  if (chartEl.value) {
    chartInstance = echarts.init(
      document.getElementById('bar-chart'),
      'macarons',
    );
    console.log(chartInstance, 'chartInstance');
    chartInstance.setOption({
      color: ['rgba(78, 199, 161, 1)'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        left: 'left',
        textStyle: {
          color: '#fff',
        },
        lineStyle: {
          opacity: 0,
        },
        data: ['访问人数', '访问次数'],
      },
      grid: {
        top: '20%',
        left: '2%',
        right: '2%',
        bottom: '2%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisTick: {
            show: false,
            alignWithLabel: true,
          },
          axisLabel: { color: '#fff' },
          axisLine: { show: false },
        },
      ],
      yAxis: [
        {
          type: 'value',
          axisTick: { show: false },
          axisLabel: { color: '#fff' },
          splitArea: { show: false },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, .14)',
              type: 'dashed',
            },
          },
          axisLine: {
            lineStyle: { width: 1 },
          },
        },
      ],
      series: [
        {
          name: '访问人数',
          data: visitUserNumData,
          type: 'line',
          smooth: true,
          symbolSize: 18,
          lineStyle: { color: '#5EEDFF' },
        },
        {
          name: '访问次数',
          data: visitNumData,
          type: 'line',
          smooth: true,
          symbolSize: 18,
          lineStyle: { color: '#FFB55E' },
        },
      ],
    });
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  // nextTick(() => {
  //   initChart();
  // });
  window.addEventListener('resize', () => chartInstance?.resize());
});

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', () => chartInstance?.resize());
});
defineExpose({
  initChart,
});
</script>

<style scoped>
#bar-chart {
  height: 100%;
}
</style>
